//
//  Project_Step5ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/22.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step6ViewController.h"
#import "Project_Step5ViewController.h"
#import "Project_Step8ViewController.h"
#import "BottomActionView.h"
#import "SystemConfigTableViewCell.h"
#import "Project_TabViewController.h"
#import "DefaultStyleTableViewCell.h"
#import "Project_Step6ViewController.h"
#import <CustomIOSAlertView.h>
#import "ProjectData.h"
#import "ProjectManager.h"
#import "MachinePriceDataResp.h"
#import <MBProgressHUD.h>
#import "UITapView.h"
#import "MainEquipSystemData.h"
#import "EditorTableViewCell.h"
#import "MachineSelectTableViewCell.h"
#import "ProductListViewController.h"
#import "ProjectContentViewController.h"
#import "ProductXlViewController.h"


@interface Project_Step6ViewController (){
    NSInteger currentSection;
    NSInteger currentRow;
    MBProgressHUD *HUD;
    BOOL priceModified;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;

@end

@implementation Project_Step6ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViews];
    
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"净水机配置";
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block Project_Step6ViewController *tmp = (Project_Step6ViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        //TODO
        [[ProjectManager manager]goLastPage];
        [tmp.navigationController popViewControllerAnimated:YES];
        
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
        [[ProjectManager manager]goNextPage];
        Project_Step8ViewController *view = [Project_Step8ViewController new];
        view.userName = kProject.name;
        view.project_id = kProject.project_id;
        view.project_name = kProject.project_name;
        [tmp.navigationController pushViewController:view animated:YES];
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStyleGrouped];
    [self.tableView registerClass:[EditorTableViewCell class] forCellReuseIdentifier:@"edit"];
    [self.tableView registerClass:[MachineSelectTableViewCell class] forCellReuseIdentifier:@"equip"];
    self.tableView.backgroundView = [[UIView alloc]init];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
}

#pragma mark - 事件响应
/**
 *  直接跳转到项目页面
 */
-(void)onBackToProject {
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (kProject.water_cleaner_equips != nil) {
        return 1 + kProject.water_cleaner_equips.count;
    }
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        //机型选择
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
        [cell setTitleStr:@"净水机" andColor:BSBlackTextColor andHintStr:nil andInputViewIsHidden:YES andInfoStr:nil andUnit:nil];
        [cell setNavigationHint:@"请选择"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    else {
        //设备cell
        //设备cell
        NSInteger equipIndex = indexPath.row - 1;
        WaterCleanerEquipData *data = [kProject.water_cleaner_equips objectAtIndex:equipIndex];
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        
        [cell setNumber:data.count andUnit:@"台"];
        [cell setTitle:data.equip_model];
        cell.SteperValueChangedBlock = ^(int number){
            if (number > 0) {
                [self updateWaterCleanerEquipCount:number andIndex:equipIndex];
            } else {
                [self deleteWaterCleanerEquip:equipIndex];
            }
        };
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = equipIndex;
        return cell;
    }
}

#pragma mark - 滑动按钮代理协议
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    //删除设备
    [self deleteWaterCleanerEquip:cell.tag];
    [cell hideUtilityButtonsAnimated:YES];
}

- (void)deleteWaterCleanerEquip:(NSInteger)index{
    WaterCleanerEquipData *equip = [kProject.water_cleaner_equips objectAtIndex:index];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:equip.equip_id forKey:@"equip_id"];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_WATER_CLEANER_EQUIP_DELETE token:[AccountManager manager].token paramDic:params resultClass:[WaterCleanerEquipData class] success:^(WaterCleanerEquipData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.water_cleaner_equips removeObjectAtIndex:index];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"删除失败！"];
    }];
}

- (void)updateWaterCleanerEquipCount:(NSInteger)count andIndex:(NSInteger)index {
    WaterCleanerEquipData *equip = [kProject.water_cleaner_equips objectAtIndex:index];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [params setValue:[equip equip_id] forKey:@"equip_id"];
    [params setValue:@(count) forKey:@"count"];
    
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_WATER_CLEANER_EQUIP_COUNT token:[AccountManager manager].token paramDic:params resultClass:[WaterCleanerEquipData class] success:^(WaterCleanerEquipData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        [kProject.water_cleaner_equips replaceObjectAtIndex:index withObject:obj];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageCenter:@"修改失败！"];
    }];
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        //机型选择
        ProductListViewController *vc = [ProductListViewController new];
        vc.product_type = @"water_cleaner_equip";
        vc.title = @"选择净水器";
        vc.series = kProject.water_cleaner_series;
        if (kProject.water_cleaner_equips != nil && kProject.water_cleaner_equips.count > 0) {
            vc.selectedGuids = [NSMutableArray new];
            for (WaterCleanerEquipData *data in kProject.water_cleaner_equips) {
                [vc.selectedGuids addObject:data.equip_id];
            }
        }
        vc.machineSelectedBlock = ^(NSArray *equips) {
            [self updateWaterCleanerEquip:equips];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)updateWaterCleanerEquip:(NSArray *)equips{
    NSMutableArray *ids = [NSMutableArray new];
    if (equips != nil && equips.count > 0) {
        for (NSDictionary *sel in equips) {
            [ids addObject:[sel objectForKey:@"Id"]];
        }
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    if (ids.count > 0) {
        [param setObject:[ids componentsJoinedByString:@","] forKey:@"ids"];
    } else {
        [param setObject:@"" forKey:@"ids"];
    }
    [param setObject:kProject.project_id forKey:@"project_id"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_WATER_CLEANER_EQUIP_SET token:[AccountManager manager].token paramDic:param resultClass:[ProjectData class] success:^(ProjectData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        kProject.water_cleaner_equips = [obj.water_cleaner_equips mutableCopy];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"数据提交失败！"];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        //机型选择
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
        return [cell getHeight];
    } else {
        //设备cell
        MachineSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"equip"];
        return [cell getHeigh];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
